#include "DomGenerator.h"

DomGenerator::DomGenerator(void)
{
	this->logger = LogFactory::getInstance()->getLog();
	XmlGrammar * grammar = new XmlGrammar();
	xmlParser = new Parser(grammar);
}

DomGenerator::~DomGenerator(void)
{
	delete xmlParser;
}

void DomGenerator::initialize(string configFileName)
{
	try {
		this->logger->info(" ************** Iniciando Zuma ************** ");
		XMLElement * zuma = this->readGameConfiguration(configFileName);
		DomainModelCreator * dmc = new DomainModelCreator();
		dmc->createDomainModel(zuma);

		list<XMLElement*> levels = zuma->getElementsByName("nivel");
		levels.reverse();
		list<XMLElement*>::iterator levelsIter;
		for(levelsIter = levels.begin();levelsIter != levels.end();	levelsIter++){
			XMLElement * level = * levelsIter;
			XmlAttribute * levelPathAttribute = level->getAttributeByName("path");
			XmlAttribute * levelValidatorPathAttribute = level->getAttributeByName("validatorPath");
			XMLElement * stage = this->readLevelConfiguration(levelPathAttribute->getValue()->c_str(), levelValidatorPathAttribute->getValue()->c_str());
			dmc->createLevelModel(stage);
		}
		delete dmc;
	}catch(XmlSintaxException se) {
		logger->error(se.getMessage());
		throw InitializationException(se.getMessage());
	}catch(XmlSemanticException e){
		logger->error(e.getMessage());
		throw InitializationException(e.getMessage());
	}catch(...) {
		logger->error("Error de inicializacion.");
		throw InitializationException("Error de inicializacion.");
	}
}

XMLElement * DomGenerator::readGameConfiguration(string configurationFileName) {
	try {
		string msg = "Comenzando parseo archivo de configuracion de juego : [";
		msg.append(configurationFileName);
		msg.append(1,']');
		logger->info(msg);

		XMLElement* root = xmlParser->ParseFile(configurationFileName);
		logger->info("Parseo finalizado.");

		DomValidator * domValidator= new DomValidator("validator.txt");
		domValidator->validateDom((*root));
		delete domValidator;

		return root;
	} catch(XmlSintaxException e) {
		throw e;
	}
}

XMLElement * DomGenerator::readLevelConfiguration(string configurationFileName, string validatorFileName) {

	try {
		string msg = "Comenzando parseo archivo de configuracion de nivel : [";
		msg.append(configurationFileName);
		msg.append(1,']');
		logger->info(msg);

		XMLElement * stage = xmlParser->ParseFile(configurationFileName);
		logger->info("Parseo finalizado.");

		DomValidator * domValidator= new DomValidator(validatorFileName);
		domValidator->validateDom(*stage);
		delete domValidator;

		return stage;
	} catch(XmlSintaxException e) {
		throw e;
	}
}